# -*- coding: utf-8 -*-
##############################################################################
#
#    OpenERP, Open Source Management Solution
#    Copyright (C) 2004-2010 Tiny SPRL (<http://tiny.be>).
#
#    This program is free software: you can redistribute it and/or modify
#    it under the terms of the GNU Affero General Public License as
#    published by the Free Software Foundation, either version 3 of the
#    License, or (at your option) any later version.
#
#    This program is distributed in the hope that it will be useful,
#    but WITHOUT ANY WARRANTY; without even the implied warranty of
#    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#    GNU Affero General Public License for more details.
#
#    You should have received a copy of the GNU Affero General Public License
#    along with this program.  If not, see <http://www.gnu.org/licenses/>.
#
##############################################################################

from openerp.osv import fields,osv
import facebook
from openerp import tools
import base64
import urllib
from cStringIO import StringIO
from operator import itemgetter

import psycopg2 as dbapi2

class project(osv.osv):
    
    _inherit = "project.project"
    _description = "Project"
    _columns = {
                'access_token':fields.char('Access Token'),     
                'category': fields.char('Category'),
                'page_id': fields.char('Page ID',size=128),
                'page_url': fields.char('Page URL',size=None),
                'likes': fields.integer('Likes'),
    }
    def get_facebook_task(self, cr, uid, ids, context=None):
        if context is None:
            context = {}
        for pageline in self.browse(cr, uid, ids, context=context):
            if pageline.page_id != None:
                fb_id = pageline.page_id
                access_token = pageline.access_token
                graph = facebook.GraphAPI(access_token)
                page = graph.get_object(fb_id)
                getojb = graph.get_connections(page["id"], "feed")
                feed = getojb['data']
                for feedline in feed:
                    feed_type = False
                    picture = ''
                    link = ''
                    object_id = ''
                    shares = 0
                    for line in feedline:
                        if line == 'message':
                            feed_type = True
                        if line == 'picture':
                            picture = feedline['picture']
                        if line == 'link':
                            link  = feedline['link']
                        if line == 'object_id':
                            object_id = feedline['object_id']
                        if line == 'shares':
                            shares  = feedline['shares']['count']
                            
                    fb_id = feedline['from']['id']
                    fb_name = feedline['from']['name']       
                    fb_user_ojb = self.pool.get('facebook.users')
                    fb_user_ids = fb_user_ojb.search(cr,uid,[('facebook_id','=',fb_id)])
                    if len(fb_user_ids) == 0:
                        fb_user_id = fb_user_ojb.create(cr,uid,{'name':fb_name,
                                                                'facebook_id':fb_id,})
                        fb_user_ids = []
                        fb_user_ids.append(fb_user_id)
                    
                    if feed_type == True:
                        feed_id      = feedline['id']
                        feed_message = feedline['message']                             
                        project_task = self.pool.get('project.task')
                        check_feed_id = project_task.search(cr,uid,[('feed_id','=',feed_id)])
                        if len(check_feed_id) == 0:
                            task_id = project_task.create(cr,uid,{'name':feed_message,
                                                         'feed_message':feed_message,
                                                         'feed_id':feed_id,
                                                         'project_id': pageline.id,
                                                         'partner_id': pageline.partner_id.id,
                                                         'picture': picture,
                                                         'link': link,
                                                         'object_id': object_id,
                                                         'shares': shares,
                                                         'facebook_id':fb_user_ids[0],
                                                         })
                            check_feed_id = []
                            check_feed_id.append(task_id)
                        else:
                            project_task.write(cr, uid, check_feed_id, {'name':feed_message,
                                                                        'feed_message':feed_message,
                                                                        'project_id': pageline.id,
                                                                        'partner_id': pageline.partner_id.id,
                                                                        'picture': picture,
                                                                        'link': link,
                                                                        'object_id': object_id,
                                                                        'shares': shares,
                                                                        'facebook_id':fb_user_ids[0],
                                                                        }, context)
                        feed_bro = project_task.browse(cr,uid,check_feed_id)
                        for feedline in feed_bro:
                            project_task.get_facebook_actions(cr,uid,[feedline.id])
            self.write(cr,uid,ids,{'likes':page['likes'],
                                   'page_url':page['link'],},context)
        return True
    
class project_task(osv.osv):
    
    _inherit = "project.task"
    _description = "Project"
    
    def _get_image_feed(self, cr, uid, ids, name, args, context=None):
        result = dict.fromkeys(ids, False)
        for obj in self.browse(cr, uid, ids, context=context):
            result[obj.id] = obj.image_facebook #or getattr(obj.product_tmpl_id, name)
        return result
    
    def _set_image_feed(self, cr, uid, id, name, value, args, context=None):
        image = tools.image_resize_image_big(value)
        res = self.write(cr, uid, [id], {'image_facebook': image}, context=context)
        return res
        
    def _get_image_comments(self, cr, uid, ids, name, args, context=None):
        result = dict.fromkeys(ids, False)
        for obj in self.browse(cr, uid, ids, context=context):
            result[obj.id] = obj.image_comments #or getattr(obj.product_tmpl_id, name)
        return result
    
    def _set_image_comments(self, cr, uid, id, name, value, args, context=None):
        image = tools.image_resize_image_big(value)
        res = self.write(cr, uid, [id], {'image_comments': image}, context=context)
        return res    

    
    def get_image_facebook_url(self, cr, uid, ids, url):
        image = False
        if url :
            if url.find('.jpg') or url.find('.bmp') or url.find('.gif'):                           
                tmp = urllib.urlopen(url).read()
                if tmp:
                    image = base64.encodestring(tmp) 
        return image
    
    def _get_image_facebook(self, cr, uid, ids, field_name, arg, context=None):
        result = {}
        for obj in self.browse(cr, uid, ids, context=context):
            result[obj.id] = self.get_image_attachment_url(cr, uid, ids, '/home/administrator/images/free_244915.jpg')
        return result
    
           
    _columns = {
                'feed_id':fields.char('Feed ID',size=None),     
                'feed_message': fields.char('Feed Message',size=None),
                'link_likes': fields.char('Link Likes',size=None),
                'link_comment': fields.char('Link Comments',size=None),
                'like_count': fields.integer('Like Count'),
                'comment_count': fields.integer('Comment Count'),
                'picture': fields.char('Feed Picture',size=None),
                'picture_facebook': fields.function(_get_image_facebook,type="binary",string="Image Facebook",),
                'link': fields.char('Link',size=None),
                'shares': fields.integer('Shares'),
                'object_id': fields.char('Object ID',size=None),
                'comment_ids': fields.one2many('facebook.comments', 'task_id', "Facebook Comments"),
                'like_ids': fields.one2many('facebook.likes', 'task_id', "Facebook likes"),
                'facebook_id': fields.many2one('facebook.users', 'Form'),
                'image_facebook': fields.binary("Facebook Image",),
                'image_comments': fields.binary("Comments Image",),                
                'image': fields.function(_get_image_feed, fnct_inv=_set_image_feed,
                    string="Big-sized image", type="binary",
                    help="Image of the product variant (Big-sized image of product template if false). It is automatically "\
                         "resized as a 1024x1024px image, with aspect ratio preserved."),
                'image_small': fields.function(_get_image_feed, fnct_inv=_set_image_feed,
                    string="Small-sized image", type="binary",
                    help="Image of the product variant (Small-sized image of product template if false)."),
                'image_medium': fields.function(_get_image_feed, fnct_inv=_set_image_feed,
                    string="Medium-sized image", type="binary",
                    help="Image of the product variant (Medium-sized image of product template if false)."),
                'image_medium2': fields.function(_get_image_comments, fnct_inv=_get_image_comments,
                    string="Medium-sized image", type="binary",
                    help="Image of the product variant (Medium-sized image of product template if false)."),                

    
    }
    def get_facebook_actions(self, cr, uid, ids, context=None):
        if context is None:
            context = {}
        for feedline in self.browse(cr, uid, ids, context=context):        
            if feedline.feed_id != None:
                fb_id = feedline.feed_id
                access_token = feedline.project_id.access_token
                graph = facebook.GraphAPI(access_token)
                feed = graph.get_object(fb_id)
                shares = 0
                picture = ''
                link = ''
                object_id = ''
                like_count = 0
                comment_count = 0
                for line in feed:
                    if line == "shares":
                        shares  = feed['shares']['count']
                    if line == 'picture':
                        picture = feedline['picture']                        
                    if line == 'comments':                 
                        comment_ojb = self.pool.get('facebook.comments')
                        for commentline in feed['comments']['data']:
                            comment_count = comment_count+1
                            fb_id = commentline['from']['id']
                            fb_name = commentline['from']['name']       
                            fb_user_ojb = self.pool.get('facebook.users')
                            fb_user_ids = fb_user_ojb.search(cr,uid,[('facebook_id','=',fb_id)])
                            if len(fb_user_ids) == 0:
                                fb_user_id = fb_user_ojb.create(cr,uid,{'name':fb_name,
                                                                        'facebook_id':fb_id,})
                                fb_user_ids = []
                                fb_user_ids.append(fb_user_id)                                   
                                
                            comment_ids = comment_ojb.search(cr,uid,[('comment_id','=',commentline['id'])])
                            if len(comment_ids) == 0:
                                comment_id = comment_ojb.create(cr,uid,{'name':commentline['message'],
                                                                       'comment_id':commentline['id'],
                                                                       'like_count':commentline['like_count'],
                                                                       'task_id': feedline.id,
                                                                       'facebook_id': fb_user_ids[0],
                                                         }) 
                                  
                                comment_ids = []
                                comment_ids.append(comment_id)                                
                            else:
                                comment_ojb.write(cr, uid, comment_ids, {'name':commentline['message'],
                                                                        'like_count':commentline['like_count'],
                                                                        'task_id': feedline.id,
                                                                        'facebook_id': fb_user_ids[0],}, context)
                    if line == 'likes':
                        likes_ojb = self.pool.get('facebook.likes')
                        fb_user_obj = self.pool.get('facebook.users')
                        
                        for likesline in feed['likes']['data']:
                            like_count = like_count + 1
                            fb_user_ids = fb_user_obj.search(cr,uid,[('facebook_id','=',likesline['id'])])
                            if len(fb_user_ids) == 0:
                                fb_id = fb_user_obj.create(cr,uid,{'facebook_id':likesline['id'],
                                                                   'name': likesline['name'],})
                                fb_user_ids = []
                                fb_user_ids.append(fb_id)
                                
                            likes_ids = likes_ojb.search(cr,uid,[('like_id','=',fb_user_ids[0]),('task_id','=',feedline.id)])
                            if len(likes_ids) == 0:
                                likes_ojb.create(cr,uid,{'like_id': fb_user_ids[0],
                                                         'task_id': feedline.id,
                                                         'name':likesline['name'],})  
                
                self.write(cr,uid,ids,{'shares':shares,'picture': picture,'like_count': like_count,'comment_count': comment_count},context)                

        return True
    
    def post_facebook(self, cr, uid, ids, context=None):
        obj_project = self.browse(cr, uid, ids, context)
        for line in obj_project:
            if line.project_id != False:
                if line.project_id.access_token != None and line.project_id.page_id != None:
                    if line.feed_id == '' or line.feed_id == None or line.feed_id == False:
                        oauth_access_token = line.project_id.access_token
                        fb_id = line.project_id.page_id
                        graph = facebook.GraphAPI(oauth_access_token)
                        messages = line.name
                        if line.image_facebook != None:
                            image = line.image_facebook
                            bin_value = image.decode('base64')
                            graph.put_photo(bin_value, messages)                         
                        else:
                            graph.put_object(fb_id, "feed", message=messages)
                            
                        feed = graph.get_connections(fb_id, "feed")
                        post = feed['data'][0]
                        self.write(cr, uid, ids, {'feed_id': post["id"],
                                                  'feed_message':messages,
                                                  'partner_id': line.partner_id.id,}, context)     
                    else:
                        raise osv.except_osv(('Warning!'),("duplicate post"))  
        return True
    
    def put_likes(self, cr, uid, ids, context=None):
        obj_project = self.browse(cr, uid, ids, context)
        for line in obj_project:
            if line.project_id != False:
                if line.project_id.access_token != None and line.project_id.page_id != None:
                    if line.feed_id != '' or line.feed_id != None or line.feed_id != False:
                        oauth_access_token = line.project_id.access_token
                        graph = facebook.GraphAPI(oauth_access_token)
                        graph.put_like(line.feed_id)
                    else:
                        raise osv.except_osv(('Warning!'),("Cannot Like Feed"))
                        
        return True
    
    def put_comments(self, cr, uid, ids, context=None):
        obj_project = self.browse(cr, uid, ids, context)
        for line in obj_project:
            if line.project_id != False:
                if line.project_id.access_token != None and line.project_id.page_id != None:
                    if line.feed_id != '' or line.feed_id != None or line.feed_id != False:
                        if line.description != '' or line.description != None:
                            messages = line.description
                            oauth_access_token = line.project_id.access_token
                            graph = facebook.GraphAPI(oauth_access_token)
                            graph.put_comment(line.feed_id,messages)
                        else:
                            raise osv.except_osv(('Warning!'),("Cannot comment feed"))
                    else:
                        raise osv.except_osv(('Warning!'),("Cannot comment feed"))
                        
        return True    

    def delete_feed(self, cr, uid, ids, context=None):
        obj_project = self.browse(cr, uid, ids, context)
        for line in obj_project:
            if line.project_id != False:
                if line.project_id.access_token != None and line.project_id.page_id != None: 
                    if line.feed_id != '' or line.feed_id != None or line.feed_id != False:
                        oauth_access_token = line.project_id.access_token
                        graph = facebook.GraphAPI(oauth_access_token)
                        graph.delete_object(line.feed_id)
                    else:
                        raise osv.except_osv(('Warning!'),("Cannot Delete Feed"))

class facebook_users(osv.osv):
    
    _name = "facebook.users"
    _description = "Facebook Users"
    _columns = {
                'name':fields.char('Name',size=None),     
                'facebook_id': fields.char('Facebook ID',size=None),
    }

class facebook_likes(osv.osv):
    
    _name = "facebook.likes"
    _description = "likes"
    _columns = {
                'name':fields.char('Name',size=None),     
                'like_id': fields.many2one('facebook.users','FB User'),
                'task_id': fields.many2one('project.task', 'Tasks'),
    }

class facebook_comments(osv.osv):
    
    _name = "facebook.comments"
    _description = "comments"
    _columns = {
                'name':fields.char('Message',size=None),     
                'comment_id': fields.char('Comment ID',size=None),
                'like_count': fields.integer('Like Count',size=None),
                'task_id': fields.many2one('project.task', 'Tasks'),
                'facebook_id': fields.many2one('facebook.users','From'),
                'categ_ids': fields.many2many('project.category', string='Tags'),                
    }

class project_category(osv.osv):
    
    _inherit = "project.category"
    _description = "Project"

    def get_tags_comments(self, cr, uid, ids, context=None): 
        obj_tags = self.browse(cr, uid, ids, context)
        for line in obj_tags:
            sql_comment_tag = "select id from facebook_comments where name like '%"+line.name+"%'"
            cr.execute(sql_comment_tag)
            comment_ids = map(itemgetter(0),cr.fetchall())
            for comment in comment_ids:
                cr.execute("""select count(*) from facebook_comments_project_category_rel 
                                where facebook_comments_id =%s and project_category_id = %s""" % (comment,line.id)) 
                counts = map(itemgetter(0),cr.fetchall())
                if counts[0] == 0:                    
                    cr.execute("""INSERT INTO facebook_comments_project_category_rel (facebook_comments_id,project_category_id)
                                    VALUES (%s,%s)""" % (comment,line.id))
            
            sql_task_tag = "select id from project_task where name like '%"+line.name+"%'"
            cr.execute(sql_task_tag)
            task_ids = map(itemgetter(0),cr.fetchall())
            for task in task_ids:
                cr.execute("""select count(*) from project_category_project_task_rel 
                                where project_task_id =%s and project_category_id = %s""" % (task,line.id)) 
                counts = map(itemgetter(0),cr.fetchall())
                if counts[0] == 0:                    
                    cr.execute("""INSERT INTO project_category_project_task_rel (project_task_id,project_category_id)
                                    VALUES (%s,%s)""" % (task,line.id))            
            
            
            
        
# vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4: